using ChikovMF.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace ChikovMF.Application.Features.Files.DeleteFile
{
    public class DeleteFileCommandHandler : IRequestHandler<DeleteFileCommand, bool>
    {
        public async Task<bool> Handle(DeleteFileCommand request, CancellationToken cancellationToken)
        {
            if (!await _fileManager.FileExists(request.PathLocation, request.FileName, cancellationToken))
            {
                return false;
            }

            var file = await _context.Files.FirstOrDefaultAsync(f => f.Name == request.FileName && f.PathLocation == request.PathLocation, cancellationToken);

            if (file != null)
            {
                _context.Files.Remove(file);

                await _context.SaveChangesAsync(cancellationToken);
            }
            
            return await _fileManager.DeleteFile(request.PathLocation, request.FileName, cancellationToken);
        }

        private readonly IFileManager _fileManager;
        private readonly IChikovMFContext _context;
        public DeleteFileCommandHandler(IFileManager fileManager, IChikovMFContext context)
        {
            _fileManager = fileManager;
            _context = context;
        }
    }
}